<template>
  <div class="custom-card">
    <div class="card-header">
      <span>用户管理</span>
    </div>

    <div class="card-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <el-skeleton animated/>
      </div>

      <!-- 权限不足提示 -->
      <div v-else-if="!hasPermission" class="no-permission">
        <el-alert
            title="权限不足"
            type="warning"
            description="您没有权限访问用户管理功能，请使用管理员账户登录。"
            show-icon
        />
      </div>

      <!-- 用户表格 -->
      <el-table v-else :data="userList" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="deleteUser(scope.row)"
                :disabled="scope.row.role === 'admin' && currentUser?.id == scope.row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 错误提示 -->
      <div v-if="error" class="error">
        <el-alert
            :title="error"
            type="error"
            show-icon
            closable
            @close="error = null"
        />
      </div>

      <!-- 刷新按钮 -->
      <div style="margin-top: 20px;">
        <el-button type="primary" @click="fetchUsers" :loading="loading">
          {{ loading ? '刷新中...' : '刷新' }}
        </el-button>
      </div>
    </div>
  </div>

  <!-- 编辑用户对话框 -->
  <el-dialog v-model="dialogVisible" title="编辑用户" width="500px">
    <el-form :model="editForm" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled/>
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="editForm.role" placeholder="请选择角色">
          <el-option label="管理员" value="admin"/>
          <el-option label="普通用户" value="user"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">保存</el-button>
        </span>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import {ref, onMounted, computed} from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'

// 用户数据
const userList = ref([])
const loading = ref(false)
const saving = ref(false)
const error = ref<string | null>(null)
const dialogVisible = ref(false)
const hasPermission = ref(true) // 默认有权限

// 编辑表单
const editForm = ref({
  id: 0,
  username: '',
  role: 'user'
})

// 获取当前用户信息
const currentUser = computed(() => {
  const userInfoStr = localStorage.getItem('userInfo')
  return userInfoStr ? JSON.parse(userInfoStr) : null
})

// 检查是否有管理员权限
const isAdmin = computed(() => {
  return currentUser.value && currentUser.value.role === 'admin'
})

// 获取用户列表
const fetchUsers = async () => {
  // 首先检查权限
  if (!isAdmin.value) {
    hasPermission.value = false
    return
  }

  hasPermission.value = true
  loading.value = true
  error.value = null

  try {
    // 从localStorage获取access token
    const accessToken = localStorage.getItem('accessToken')

    if (!accessToken) {
      throw new Error('未找到访问令牌，请重新登录')
    }

    // 发送请求获取用户列表
    const response = await axios.get('/api/users/', {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    })

    // 根据接口文档处理响应
    if (response.data.success) {
      userList.value = response.data.data
    } else {
      throw new Error(response.data.message || '获取用户列表失败')
    }
  } catch (err: any) {
    console.error('获取用户列表失败:', err)

    // 处理不同类型的错误
    if (err.response) {
      switch (err.response.status) {
        case 401:
          error.value = '未授权，请重新登录'
          break
        case 403:
          error.value = '权限不足'
          hasPermission.value = false // 设置权限不足标志
          break
        case 500:
          error.value = '服务器内部错误'
          break
        default:
          error.value = err.response.data.message || '获取用户列表失败'
      }
    } else if (err.request) {
      error.value = '网络错误，请检查网络连接'
    } else {
      error.value = err.message || '获取用户列表失败'
    }

    // 显示错误消息
    if (err.response?.status !== 403) {
      ElMessage.error(error.value)
    }
  } finally {
    loading.value = false
  }
}

// 编辑用户
const editUser = (user: any) => {
  editForm.value = {
    id: user.id,
    username: user.username,
    role: user.role
  }
  dialogVisible.value = true
}

// 保存用户修改
const saveUser = async () => {
  saving.value = true
  try {
    // 从localStorage获取access token
    const accessToken = localStorage.getItem('accessToken')

    if (!accessToken) {
      throw new Error('未找到访问令牌，请重新登录')
    }

    // 发送更新请求
    const response = await axios.put(`/api/user/update/`, {
      id: editForm.value.id,
      role: editForm.value.role
    }, {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    })

    if (response.data.success) {
      ElMessage.success('用户信息更新成功')
      dialogVisible.value = false
      fetchUsers() // 刷新用户列表
    } else {
      throw new Error(response.data.message || '更新失败')
    }
  } catch (err: any) {
    console.error('更新用户失败:', err)

    let errorMessage = '更新用户失败'
    if (err.response) {
      if (err.response.status === 403) {
        errorMessage = '权限不足，无法更新用户信息'
      } else {
        errorMessage = err.response.data.message || errorMessage
      }
    } else if (err.request) {
      errorMessage = '网络错误，请检查网络连接'
    } else {
      errorMessage = err.message || errorMessage
    }

    ElMessage.error(errorMessage)
  } finally {
    saving.value = false
  }
}

// 删除用户
const deleteUser = (user: any) => {
  // 防止用户删除自己
  if (currentUser.value && currentUser.value.id == user.id) {
    ElMessage.warning('不能删除自己的账户')
    return
  }

  ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      // 从localStorage获取access token
      const accessToken = localStorage.getItem('accessToken')

      if (!accessToken) {
        throw new Error('未找到访问令牌，请重新登录')
      }

      // 发送删除请求
      const response = await axios.delete(`/api/users/${user.id}/`, {
        headers: {
          'Authorization': `Bearer ${accessToken}`
        }
      })

      if (response.data.success) {
        // 删除成功后刷新列表
        ElMessage.success('删除成功')
        fetchUsers()
      } else {
        throw new Error(response.data.message || '删除失败')
      }
    } catch (err: any) {
      console.error('删除用户失败:', err)

      let errorMessage = '删除用户失败'
      if (err.response) {
        if (err.response.status === 403) {
          errorMessage = '权限不足，无法删除用户'
        } else {
          errorMessage = err.response.data.message || errorMessage
        }
      } else if (err.request) {
        errorMessage = '网络错误，请检查网络连接'
      } else {
        errorMessage = err.message || errorMessage
      }

      ElMessage.error(errorMessage)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.custom-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  padding: 20px;
}

.loading {
  padding: 20px 0;
}

.error {
  margin: 20px 0;
}

.no-permission {
  padding: 20px 0;
}
</style>
